function to_replay(o)
{
    var $obj=$(o);
    var $content=$obj.parents("form").find("textarea[name=eval]");
    if($content.val().length >300||$content.val().length <5)
    {
       alert('提示请输入5-300个字符');
       return false;
    }
    var date=$obj.parents("form").serialize();
    $.getJSON(consts('act')+'/Goods/Insert_Replay/?callback=?',date,function(date)
    {
        switch(date.msg)
        {
            case 0:
                alert('请您5分钟后再继续发表回复^_^');
                break;
            case 1 :
                _common_box('请您登录后继续刚才的操作');
                pop_login(1,'');
              // alert('请登录后回复');
               break;
            case 2 :
               alert('不能回复自己的评论');
               break;
            case 3 :
               alert('回复成功');
               $obj.parents(".c_reply_form").hide(500);
               break;
            default:
               alert('系统测试ing');
               break;
        };
    });
}
function is_help(o)
{
    var $obj=$(o);
    var help=parseInt($obj.find("strong").html());
    var cid   =$obj.attr("rel");
    var $help =$obj.find("strong");
    $.getJSON(consts('act')+'/Goods/Comment_is_help/?callback=?',{"cid":cid},function(date){
		 switch(date.msg){
           case 0:
               alert('您已经评价啦^_^');
               break;
           case 1 :
               _common_box('请您登录后继续刚才的操作');
               pop_login(1,'');
               break;
           case 2 :
               alert('您已经评论过了，请不要重复评论');
               break;
           case 3 :
               alert('评价成功');
               help+=1;
               $help.html(help);
               break;
           default:
               alert('系统测试ing');
               break;
		 };
	});
}
function giveAReply(id)
{
    $replay_ret=$("#replyFor"+id);
    $.getJSON(consts('act')+'/Ajax/checkLogin?callback=?',function (_data) {
    if(_data.status=='1')
    {
        $replay_ret.show();
    }
    else
    {
        _common_box('请您登录后继续刚才的操作');
        pop_login(1,'');
        return false;
    }
    });
}

//显示提问输入框
function showQuestionForm(){
	$(".writeQuestion").show();
}
//关闭回复输入框
function closeRelpy(id)
{
    $("#replyFor"+id).hide();
}

//详情页AJAX商品获取价格区块
function getGoodsPrice(goods_sn){
    var params={goods_sn:goods_sn};
    $.ajax({type: "GET",url: consts("act")+"/Price/getGoodsPrice?r="+Math.random()+"&callback=?",data: params,dataType :"json",cache :"false",success : function(data){
		$("#mainright_info").html(data.data);
        $("#current_img").attr({'src':data.thumb_url,'jqimg':data.jqimg});
		if( typeof( data['promotions'] ) != 'undefined' && data['promotions'] != null ){
			$.each(data['promotions'],function(i,n){
				$("#promotionsList").append('<a class="red" slId="' + n.pid + '" href="' + n.url + '" title="' + n.n + '" target="_blank">' + n.n + '</a>&nbsp;&nbsp;  ');
			});
			clickSetCookie();
		}
    },error:function(){
        alert("加载失败");
        return;
    }});
}
//详情页秒杀倒计时相关
function secondtime()
{
    var is_timeout = false;
    var maxtime =$("input[name='last_time']").val(); //剩余时间的时间戳
    var is_start = $("input[name='start_time']").val();
    if(is_start>0)
    {
      msg="秒杀还没有开始！";
      $("#count_down").html(msg);
    }
    else
    {
      CountDown();
    }
    function my_date_format(str,str_color)
    {
      var mydate = str || '0';
      var color = '' || str_color;
      if(mydate < 10)
      {
        mydate = '0' + mydate;
      }
      if(color != '' || color!=undefined)
      {
        mydate = '<span class="'+ str_color +'">'+ mydate +'</span>';
      }
      return mydate;
    }
    function CountDown()
    {
      var oneDay=60*60;
      if(maxtime>0)
      {
          var e_day = maxtime / (oneDay*24);
          var drsold = Math.floor(e_day); //得到剩余天数
          var e_hrsold = (e_day-drsold)*24;
          var hrsold = Math.floor(e_hrsold); //得到剩余小时(整数)
          var e_minsold=(e_hrsold-hrsold)*60;
          var minsold=Math.floor((e_hrsold-hrsold)*60);  //得到尾剩余分数(整数)
          var seconds=Math.floor((e_minsold-minsold)*60); //得到尾剩余秒数(整数)

          var msg = '';
          if(e_day >=1)
          {
            msg += '<span class="second_red">'+ drsold +'</span>&nbsp;天&nbsp;';
          }
          msg += my_date_format(hrsold, 'second_red')+"&nbsp;时&nbsp;" + my_date_format(minsold, 'second_red') + "&nbsp;分&nbsp;" + my_date_format(seconds, 'second_red') + "&nbsp;秒&nbsp;";

          $("#count_down").html(msg);
          --maxtime;
      }
      else if(maxtime == 0)
      {
          is_timeout = false;
          //alert(msg);
          $("#count_down").html("秒杀已经结束！");
          //window.location.href="__SELF__";
          return ;
      }
      else if(maxtime < 0)
      {
          msg="秒杀已经结束！";
          $("#count_down").html(msg);
          is_timeout = true;
      }
      setTimeout(CountDown,1000);
    }
}
//获取邮费
function getfee(region_id,region_name)
{
    $.ajax({
    type: "GET",
    url: consts('act')+"/Ajax/get_fee?time="+Math.random()+"&callback=?",
    data: {region_id:region_id},
    dataType :"json",
    cache :"false",
    success : function(data,textStatus)
    {
        var fee='';
        var ems='';
        if(data!=null){
        fee=parseInt(data[0].shipping_fee)+' 元';
        ems=parseInt(data[0].ems_fee)+' 元';

        $("#fee_tag").html(fee);
        $("#ems_tag").html(ems);
        $("#nowcity").html(region_name);
        }
        $("#J_DestPanel").fadeOut(350);
    },
    error:function()
    {
        alert("加载失败");
        return ;
    }
    });
}
//切换js
function changeInfoTab(obj, other)
{
    $(".info_div").hide();
    $("#infotitlenew").find("span").each(function()
    {
        $(this).removeClass("selelct");
    });
    if(typeof other!= 'undefined')
    {
        $("#"+other+"_span").addClass("selelct");
        $("#"+other+"_div").show();
    }
    else
    {
        $("#"+$(obj).attr('id')+"_span").addClass("selelct");
        $("#"+$(obj).attr('id')+"_div").show();
    }
}
//详情页留言等列表AJAX获取内容
function ajaxGetList(listtype,goods_sn,page,total_page,order_by)
{
    var params={goods_sn:goods_sn,page:page,total_page:total_page,order_by:order_by};
    $.ajax({
        type: "GET",
        url: consts('act')+"/Ajax/cartAjax?time="+Math.random()+"&callback=?&ajaxtype="+listtype,
        data: params,
        dataType :"json",
        cache :"false",
        success : function(data,textStatus) {
            switch(listtype){
                case 'comment'://评价列表
					$('#comments_div').html('');
					$("#comments_div").html( data );
					bg.utils.scrollToIt('#comments_anchor');
                break;
                case 'commentGroup':
                    var comments='';
                    var suit=Array('偏小','大小合适','偏大');
                    var img_str = '';

                    $(".comments_info").html('');
                    $(data.list).each(function(i){
                                 //构造评论
                        comments+="<dl class='comments_list'>" +
                                       "<dt class='left'>" +
                                       "<a href='comments/?user_id=" + this.user_name +"'>";
                                        switch(this.rank){
                                                   case 1:
                                                      img_str = "<img  src='/Public/style/images/member_normal.jpg' alt='普通会员'>";
                                                       break;
                                                   case 2:
                                                      img_str = "<img src='/Public/style/images/member_vip.jpg' alt='vip会员' />";
                                                       break;
                                                   case 3:
                                                      img_str = "<img src='/Public/style/images/member_svip.jpg' alt='vip会员' />";
                                                       break;
                                                   default:
                                                       break;
                                         }

                        comments += img_str;
                        comments += "<span>"+ this.user_name +"</span></a></dt>" +
                                        "<dd class='right'>" +
                                                "<div class='c_author'>" +
                                                    "<h3 class='c_title'>"+(this.title?this.title:"好评！")+"</h3>" +
                                                    (this.satisfaction_rank>0?"<span class='c_stars comments_bg stars_m_"+this.satisfaction_rank+"'></span>":"")+
                                                    "<span class='c_date'>"+this.add_time_str+"</span>" +
                                                "</div>" +
                                                " <div class='c_content'> " +this.content+"</div>"+
                                                " <ul class='c_list c_customer'>"+
                                                    (parseInt(this.height) >0?"<li>TA身高："+this.height+"cm</li>":"") +
                                                    (parseInt(this.weight) >0?"<li>体重："+this.weight+"kg</li>":"") +
                                                    (this.goods_color.length>0?"<li>购买颜色："+this.goods_color+"</li>":"") +
                                                    (this.goods_style.length>0?"<li>购买尺码："+this.goods_style+"</li>":"") +
                                                    (parseInt(this.suit)>0 ? "<li>尺码大小：" + suit[parseInt(this.suit)-1] + " </li>":"")+
                                                "</ul>" +
                                                "<div class='c_act'>" +
                                                        "<em>此评价对我</em> <a rel='"+this.comment_id+"' class='btn btn_common_small is_help' onclick='is_help(this)'><span>有帮助(<strong id='helps'>"+this.is_help+"</strong>)</span></a>" +
                                                        "<a onclick='giveAReply(\"comments_"+(i+1)+"\")' class='btn btn_common_small c_reply' ><span>回复</span></a>" +
                                                "</div>" +
                                                "<dl id='replyForcomments_"+(i+1)+"' class='c_reply_form'>" +
                                                       "<form>" +
                                                          "<input type='hidden' value='" + this.comment_id + "' name='pid'>" +
                                                          "<dt><strong>发表回复</strong><span>（长度在5-300个字符之间）</span></dt>" +
                                                          "<dd class='mt5'><textarea class='tarea1' rows='5' name='eval'></textarea></dd>" +
                                                          "<dd class='mt10'>" +
                                                                "<a class='btn btn_important_small_red mr10' onclick='to_replay(this)'><span>提交</span></a> &nbsp;" +
                                                                "<a onclick='closeRelpy(\"comments_"+(i+1)+"\")' class='btn btn_common_small' ><span>关闭</span></a>" +
                                                          "</dd>" +
                                                       "</form>" +
                                                "</dl><div class='comments_bg arrow'></div>";
                                             var repleys='';
                                             var total=this.comment_replays_nums[0]['total'];
                                             $(this.comment_replays.list).each(function(j){
                                                 if(j<=4){
                                                      repleys+="<dl class='c_reply_list'>" +
                                                                    "<dt><span class='c_r_1'>"+(total-j)+".</span><a class='c_r_2' href='comments/?user_id="+this.user_id+"'>"+this.user_id+"</a>" +
                                                                        "<span class='c_r_3'>回复说：</span>" +
                                                                        "<span class='c_r_4'>"+this.add_times+"</span>" +
                                                                    "</dt>" +
                                                                    "<dd> "+this.content+"</dd>" +
                                                                "</dl>";
                                                 }
                                             })                           //构造回复
                                             repleys= repleys?'<div class="c_reply_list_box">'+repleys+'</div>':'';
                        comments += repleys;

                        comments +=total>5?"<div class='c_more'><a href='View_Replays?good_id="+this.goods_sn+"&comment_id="+this.comment_id+"' class='btn_simple'>查看全部 "+total+" 条回复 >></a></div>":"";

                        comments +=	"</dd>" +
                                    "</dl>";

                    });
                    $(".comments_info").html(comments);
                    str = data.pagelist;
                    $(".bottom-pager").html(str);
                    location.hash="fl";
                break;
                case 'question'://问答列表
                case 'questionGroup':
                    $(".question_list").remove();
                    $(data.list).each(function(){
                        str = "<dl class='question_list'><dt><span class='icon icon_question_flat'></span><div class='con-text'>"+this.content+"</div><div class='con-u'>"+this.user_name+"&nbsp;&nbsp;&nbsp;"+this.add_time_str+"</div></dt>";
                        if(this.answer != null && this.answer != '') {
                            str += "<dd> <span class='icon icon_answer_flat' ></span><div class='con-text'>" + this.answer + "</div><div class='con-u'>邦购客服</div></dd>";
                        }
                        str += "</dl>";
                        $(".question_fd_info").before(str);
                    })
                    str = '<div class="bottom-pager" style="padding:5px;float:right">' + data.pagelist + '</div>';
                    $(".question_fd_info").html(str);
                break;
                case 'tradingGroup'://搭配交易记录列表
                    $(".buy_record").html('');
                    var str = '<table cellspacing="0" cellpadding="0"><tbody><tr><td width="25%">用户ID</td><td width="60%"><table width="100%"><tr><td style="width:80%">购买信息</td><td style="width:20%;text-align:center">购买数量</td></tr></table></td><td width="15%" style="text-align:center">购买时间</td></tr>';
                    $(data.list).each(function(){
                        str += '<tr><td width="25%">' + this.user_id + '</td><td width="60%"><table width="100%">';
                        $(this.goods).each(function(){
                            str += '<tr><td style="width:80%;border-top:none">' + this.goods_name + '<br>';
                            str += '<font color="#666">颜色：' + this.goods_color_name + '　尺寸：' + this.goods_size_name + '</font></td>';
                            str += '<td style="width:20%;border-top:none;text-align:center">' + this.goods_number + '</td></tr>';
                        });
                        str += '</table></td> <td width="15%" style="text-align:center">' + this.add_time + '</td></tr>';
                    });
                    str += '<td colspan="3"><div class="bottom-pager" style="padding:5px;"><div style="float:right">' + data.pagelist + '</div></div></td></tr></tbody></table>';
                    $(".buy_record").html(str);
                break;
            }
        },
        error:function(){}
    });
}
//显示套装弹窗
function showGroupTable(goods_sn,rec_id)
{
    var params={goods_sn:goods_sn,rec_id:rec_id};
    $.ajax({type: "POST",url: consts('url')+"/group_info/?time="+Math.random(),data: params,dataType :"xml",cache :"false",
    success : function(data,textStatus)
    {
        $("#group_box").html($(data).find('root').text());
        $("#group_bob-big").css({"opacity":"0.5","height":$(document).height(),"width":$(document).width(),"position":"absolute","background":"#000","left":"0","top":"0","z-index":"999"}).show();
    },
    error:function()
    {
        alert("加载失败");
    }
    });
}
//显示地区选择框
function showcountry()
{
    $("#J_DestPanel").toggle(0);
}
//AJAX颜色尺寸切换
function choosegroup(type,code,name,goods_sn)
{
    var params={type:type,code:code,goods_sn:goods_sn};
    $.ajax({
        type: "POST",
        url: consts('url')+"/group_info?time="+Math.random()+"&act=change_color_size",
        data: params,
        dataType :"json",
        cache :"false",
    success : function(data,textStatus)
    {
        if(type=='color')
        {
            $("#gsize_ul_"+goods_sn).empty();
            $(data).each(function()
            {
            var cla='';
            if($("#gsize_"+goods_sn).val()==this.size_code)
            {
                cla="class='selected'";
            }
            $("#gsize_ul_"+goods_sn).append("<li><a id='gsize_"+goods_sn+"_"+this.size_code+"' "+cla+"  href='javascript:void(0)' onclick=\"choosegroup('size','"+this.size_code+"','"+this.size_name+"','"+goods_sn+"')\" >"+this.size_name+"</a></li>");})
            $("#gcolor_"+goods_sn).val(code);
            $("#choose_color_show_"+goods_sn).html(name);
            $("#gcolor_ul_"+goods_sn).find("a").removeClass();
            $("#gcolor_"+goods_sn+"_"+code).attr('class','selected');
        }
        else
        {
            $("#gcolor_ul_"+goods_sn).empty();
            $(data).each(function(){
            var cla=''
            if($("#gcolor_"+goods_sn).val()==this.color_code)
            {
                cla="class='selected'";
            }
            $("#gcolor_ul_"+goods_sn).append("<li><a id=\"gcolor_"+goods_sn+"_"+this.color_code+"\"  "+cla+"  href='javascript:void(0)' onclick=\"choosegroup('color','"+this.color_code+"','"+this.color_name+"','"+goods_sn+"')\" ><img  title='"+this.color_name+"' src='"+this.thumb_url+"' width=20 height=20 /><span>"+this.color_name+"</span></a></li>")
            })
            $("#gsize_"+goods_sn).val(code);
            $("#choose_size_show_"+goods_sn).html(name);
            $("#gsize_ul_"+goods_sn).find("a").removeClass();
            $("#gsize_"+goods_sn+"_"+code).attr('class','selected');
        }
    },
    error:function()
    {
        alert("加载失败");
        return false;
    }
    });
}
function choosegroupnew(type,code,name,goods_sn,r_code)
{
    if(type=='color' && code == $("#gcolor_"+goods_sn).val())
    {
        $("#gcolor_"+goods_sn).val('');
        $("#imgurl_" + goods_sn).attr('src', $("#imgurl_" + goods_sn).attr('ownimg'));
        choosegroupnewcancel(goods_sn);
        return;
    }
    else if(type=='size' && code == $("#gsize_"+goods_sn).val())
    {
        $("#gsize_"+goods_sn).val('');
        choosegroupnewcancel(goods_sn);
        return;
    }
    var params={type:type,code:code,r_code:r_code,goods_sn:goods_sn,act:'change_color_size',time:Math.random()};
    $.getJSON( consts('act')+"/Goods/group_info?callback=?",params,
    function(data)
    {
        if(type=='color')
        {
            $("#gsize_ul_"+goods_sn).empty();
            $(data['size_list']).each(function()
            {
                var cla='';
                if (this.available == 0)
                {
                    $("#gsize_ul_"+goods_sn).append("<a id='gsize_"+goods_sn+"_"+this.size_code+"' class='selected_b' >"+this.size_name+"</a>");
                }
                else
                {
                    if($("#gsize_"+goods_sn).val()==this.size_code)
                    {
                        cla="class='select'";
                    }
                    $("#gsize_ul_"+goods_sn).append("<a id='gsize_"+goods_sn+"_"+this.size_code+"' " + cla + " onclick=\"choosegroupnew('size','"+this.size_code+"','"+this.size_name+"','"+goods_sn+"','"+code+"')\" >"+this.size_name+"</a>");
                }
            })
            $("#gcolor_"+goods_sn).val(code);
            $("#sel_yanse_"+goods_sn).html('颜色：' + name);
            $("#gcolor_ul_"+goods_sn).find(".select").removeClass();
            $("#gcolor_"+goods_sn+"_"+code).attr('class','select');
            $("#imgurl_" + goods_sn).attr('src', $("#imgurl_color_" + goods_sn + '_' + code).attr('bigimg'));
        }
        else
        {
            $("#gcolor_ul_"+goods_sn).empty();
            $(data['color_list']).each(function(){
            var cla=''
            if (this.available == 0) {
            $("#gcolor_ul_"+goods_sn).append("<a id=\"gcolor_"+goods_sn+"_"+this.color_code+"\"  class='selected_b'><img  title='"+this.color_name+"' src='"+this.thumb_url+"' width=32 height=32 class='prodimg' /></a>")
            } else {
            if($("#gcolor_"+goods_sn).val()==this.color_code){
            cla="class='select'";
            }
            $("#gcolor_ul_"+goods_sn).append("<a id=\"gcolor_"+goods_sn+"_"+this.color_code+"\"  "+cla+" onclick=\"choosegroupnew('color','"+this.color_code+"','"+this.color_name+"','"+goods_sn+"','"+code+"')\" ><img id='imgurl_color_" + goods_sn + "_" + this.color_code + "'  title='"+this.color_name+"' src='"+this.thumb_url+"' bigimg='" + this.big_thumb_url + "' width=32 height=32 /></a>")
            }
            })
            $("#gsize_"+goods_sn).val(code);
            //$("#avai_num_"+goods_sn).html(data['avl_num']);
            $("#sel_chima_"+goods_sn).html('尺码：' + name);
            $("#gsize_ul_"+goods_sn).find(".select").removeClass();
            $("#gsize_"+goods_sn+"_"+code).attr('class','select');
        }
    }
    );
}
function choosegroupnewcancel(goods_sn)
{
    var params={type:'color_size',color_code:$("#gcolor_"+goods_sn).val(),size_code:$("#gsize_"+goods_sn).val(),goods_sn:goods_sn,act:'change_color_size',time:Math.random()};
        $.getJSON( consts('act')+"/Goods/group_info?callback=?",params,function(data) {
        $("#gsize_ul_"+goods_sn).empty();
        $(data['size_list']).each(function(){
            var cla='';
            if (this.available == 0) {
                $("#gsize_ul_"+goods_sn).append("<a id='gsize_"+goods_sn+"_"+this.size_code+"' class='selected_b'  >"+this.size_name+"</a>");
            } else {
                if($("#gsize_"+goods_sn).val()==this.size_code){
                    cla="class='select'";
                }
                $("#gsize_ul_"+goods_sn).append("<a id='gsize_"+goods_sn+"_"+this.size_code+"' " + cla + "  onclick=\"choosegroupnew('size','"+this.size_code+"','"+this.size_name+"','"+goods_sn+"','"+$("#gcolor_"+goods_sn).val()+"')\" >"+this.size_name+"</a>");
            }
        });
        $("#gcolor_ul_"+goods_sn).empty();
            $(data['color_list']).each(function(){
                var cla=''
                if (this.available == 0) {
                    $("#gcolor_ul_"+goods_sn).append("<a id=\"gcolor_"+goods_sn+"_"+this.color_code+"\"  class='selected_b' ><img  title='"+this.color_name+"' src='"+this.thumb_url+"' width=32 height=32 class='prodimg' /></a>")
                } else {
                    if($("#gcolor_"+goods_sn).val()==this.color_code){
                        cla="class='select'";
                    }
                    $("#gcolor_ul_"+goods_sn).append("<a id=\"gcolor_"+goods_sn+"_"+this.color_code+"\"  "+cla+"  onclick=\"choosegroupnew('color','"+this.color_code+"','"+this.color_name+"','"+goods_sn+"','"+$("#gsize_"+goods_sn).val()+"')\" ><img id='imgurl_color_" + goods_sn + "_" + this.color_code + "'  title='"+this.color_name+"' src='"+this.thumb_url+"' bigimg='" + this.big_thumb_url + "' width=32 height=32 /></a>")
                }
        });

        //$("#avai_num_"+goods_sn).html(data['avl_num']);
        if($("#gcolor_"+goods_sn).val() == '') $("#sel_yanse_"+goods_sn).html('请选择颜色');
        if($("#gsize_"+goods_sn).val() == '') $("#sel_chima_"+goods_sn).html('请选择尺码');
    });
}
function change_group_num()
{
    var num=$("#group_num").val()
    $(".goods_num").each(function(){$(this).val($("#pre_"+$(this).attr('id')).val()*num)})
}
function close_group_box()
{
    $("#group_box").empty();
    $("#group_bob-big").hide();
}
//尺码转换器
function show_measure(goods_sn) {
	$.getJSON(consts('act')+'/Ajax/checkLogin?callback=?',function (_data) {
		if(_data.status=='1') {
			$.getJSON(consts('act')+'/Price/size_conversion?callback=?&goods_sn='+goods_sn,function (data) {
				$("#measureDiv").html(data.data);
			});
			$("#measureBox").show();
			ajaxRoleInfo(0);
		} else {
			_common_box('请您登录后继续刚才操作');
			pop_login(1,'');
		}
	});
}
//检查输入数量
function _check_number()
{
   $("#reduce_but").click(function()
    {
        var numbers = $("#goods_number").val();
        if(numbers > 1)
        {
            numbers--;
            $("#goods_number").val(numbers);
        }
    })
    $("#add_but").click(function()
    {
        var i=$("#goods_number").val();
        if(i<20)
        {
            i++;
            $("#goods_number").val(i);
        }
        else
        {
            alert("单件商品限购20件！");
            return;
        }
    })
}

/*************尺码转换器 开始**********************/
function hide_measure() {
	$("#measureBox").hide();
}

function showClick(name1,name2) {
	$('#'+name1+'_show #'+name1+'_div').removeClass('input_disable')
	$('#'+name1+'_show #'+name1+'_div').attr('name',name1);
	$('#is_'+name1+'_show').attr('checked',true);
	$('#'+name2+'_show #'+name2+'_div').removeAttr('checked');
	$('#'+name2+'_show #'+name2+'_div').addClass('input_disable')
	$('#'+name2+'_show #'+name2+'_div').attr('name','');
	$('#'+name2+'_show #'+name2+'_div').removeClass('invalid');
	$('#'+name2+'_show .errorinfo').html('');
	$('#'+name2+'_show #'+name2+'_div').val('');
}
//选择体型
function body_val(obj,v) {
	$('#body_feature_'+v).show().siblings().hide();
	$('#body_type_name').val($('#body_name_'+v).html());
	$('#body_name a').removeClass('cur');
	$('#body_'+v).addClass('cur');
}
//保存用户转换数据
function endbtn() {
	if($('#end_check').attr('checked')==true && $('#end_role_id').val()!='' && $('#end_is_save').val()=='1' ) {
		var params={role_id:$('#end_role_id').val(),sex:$('#end_sex').val(),transform_type:$('#end_transform_type').val(),height:$('#end_height').html(),weight:$('#end_weight').html(),bust:$('#end_bust').html(),waist:$('#end_waist').html(),hip_type:$('#end_hip_type').html(),body_type:$('#end_body_type').html()};
		$.getJSON( consts('act')+"/Price/saveRole?time="+Math.random()+"&callback=?",params,function(data){
			if(data.status==0) alert(data.message);
			else $('#end_is_save').val('0');
		});
	}
	$('#measureBox').hide();
}
//ajax获取身材信息
function ajaxRoleInfo(value) {
	var params = {role_type:value};
	$.getJSON( consts('act')+"/Price/selsectRole?time="+Math.random()+"&callback=?",params,function(data){
		if(data.status==1){
			if( typeof(data.height)=="undefined" || data.height=='0' )
				$('#height_div').val('');
			else
				$('#height_div').val(data.height);
			if( typeof(data.weight)=='undefined' || data.weight=='0' )
				$('#weight_div').val('');
			else
				$('#weight_div').val(data.weight);
			if( typeof(data.bust)=='undefined' || data.bust=='0' )
				$('#bust_div').val('');
			else
				$('#bust_div').val(data.bust);
			if( typeof(data.waist)=='undefined' || data.waist=='0' )
				$('#waist_div').val('');
			else
				$('#waist_div').val(data.waist);
		}
	});
}
//下拉二级收缩-暂时删除
$('.sortGroup .sortGroupTitle').each(function(){
	$(this).click(function(){
		if( $(this).next('ul:first').css('display')=='block' )
			$(this).next('ul:first').hide();
		else if( $(this).next('ul:first').css('display')=='none' )
			$(this).next('ul:first').show();
	});
});
//尺码
function _size(){
    //显示上装胸围
    $('#is_bust_show').bind('click',function(){
        showClick('bust','weight');
    });
    //显示上装体重
    $('#is_weight_show').bind('click',function(){
        showClick('weight','bust');
    });
    //尺码转换器重填
    $('#retrun_btn').bind('click',function(){
        var type = $('#end_transform_type').val()=='1' ? 'up' : $('#end_transform_type').val()=='2' ? 'down' : '';
        $('#'+type+'1_div').show();
        $('#end_div').hide();
    });
}
/*************尺码转换器 结束**********************/


/*************商品评论 开始**********************/
//添加评论等
function addcomment(question_type,comment_type,goods_sn)
{
    var comment=$("#commenttext").val();
    if(comment.length > 250)
    {
        alert("提问不能超过250个字！");
        return;
    }
    $.ajax({
        type: "GET",
        url: consts('act')+"/Ajax/cartAjax?time="+Math.random()+"&callback=?&ajaxtype=add_comment",
        data: {question_type:question_type,comment_type:comment_type,goods_sn:goods_sn,comment:comment},
        dataType :"json",
        cache :"false",
        success : function(data,textStatus) {
            switch(data){
                case 1:
                    alert("提问成功！请等待回复");
                    $("#commenttext").val("");
                    break;
                case 2:
                    _common_box('请您登录后继续刚才的操作');
                    pop_login(1,'');
                    break;
                case 3:
                    alert("请填写提交内容，内容不能为空！");
                    break;
            }
        },
        error:function(){

        }
    })
}


//弹出报错窗口
function show_comments_error(){
	var _html = ''
	_html += '<div id="comments_error">'
	_html += '	<div class="hd"><span>我要评价</span> <a onclick="remove_comments_error()">关闭</a></div>'
	_html += '	<div class="bd">'
	_html += '		<div class="c_e_left"><em class="comments_bg"></em></div>'
	_html += '			<div class="c_e_right">'
	_html += '				<h3>您暂不能对该商品进行评价，可能有以下原因：</h3>'
	_html += '				<p>1.您可能没有在邦购商城购买过该商品；</p>'
	_html += '				<p>2.购买时间已经超过3个月；</p>'
	_html += '				<p>3.您已经评价过该商品。</p>'
	_html += '				<p class="mt10"><a href="javascript:;" class="btn btn_common" onclick="remove_comments_error()"><span>确定</span></a></p>'
	_html += '			</div>'
	_html += '		</div>'
	_html += '	</div>'
	$("#comments_error").remove();
	$("#customers_comment").append(_html);
}

//关闭报错窗口
function remove_comments_error(){
	$("#comments_error").remove();
}

	//评论条件
	function verify_comment_show(good_sn){
		$.getJSON(consts('act')+'/Goods/pubComment/?callback=?',{"goods_sn":good_sn},function(data){
			switch(data.msg){
				case '0':
					_common_box('请您登录后继续刚才的操作');
					pop_login(1,'');
					break;
				case '1':
					show_comments_error();
					break;
				case '2':
					location.href=consts('member')+"/MemberTrade/pubComment.shtml?order_sn="+data.order_sn+"&sku_sn="+data.sku_sn;
					break;
				default:
					break;
			}
		});
	}


/*************商品评论 结束**********************/



// 缺货状态下
bg.common.goods_oos = {};

bg.common.goods_oos.doms = {

    // 缺货状态下的界面处理
    details_auto       : "#details_auto",           // 右侧信息区域
    productinfo_div    : "#productinfo_div",        // 标题 - 商品详情
    customers_comment  : "#customers_comment",      // 标题 - 顾客评论
    inquiry_div        : "#inquiry_div",            // 标题 - 商品咨询
    know_div           : "#know_div",               // 标题 - 购物须知
    productinfo_anchor : "#productinfo_anchor",     // 锚点 - 商品详情
    comments_anchor    : "#comments_anchor",        // 锚点 - 顾客评论
    inquiry_anchor     : "#inquiry_anchor",         // 锚点 - 商品咨询
    know_anchor        : "#know_anchor",            // 锚点 - 购物须知
    details_info_title : "#details_info_title",     // 缺货状态下的详情标题
    icon_sold_out      : ".icon_sold_out",          // 售罄icon
    sider              : "#details_sider",          // 侧栏
    
    // 默认显示与隐藏
    init: function() {
        // 缺货下默认隐藏的模块
        $(this.sider).hide();
        $(this.productinfo_div).hide();
        $(this.customers_comment).hide();
        $(this.inquiry_div).hide();
        $(this.know_div).hide();
        $(this.comments_anchor).hide();
        $(this.inquiry_anchor).hide();
        $(this.know_anchor).hide();    
        $(this.productinfo_anchor).hide();
        this.show_details();
    
        // 缺货下默认显示的模块
        $(this.icon_sold_out).css({
          position: "absolute",
          display: "block"
        });

        // 查看商品详情
        var _this = this;
        $(".view_goods_details").click(function(e){
            _this.show_details();
            e.preventDefault();
            bg.utils.scrollToIt("#productinfo_div", 1000);
        });

        // 关闭商品详情
        $(".close_btn").click(function(e){
            _this.hide_details();
            e.preventDefault();
        });
    },    

    // 显示详情
    show_details: function() {
        $(this.details_info_title).show();
        $(this.productinfo_div).show();
        $(this.details_auto).show().css("width","100%");
        $(this.productinfo_div).css("border","none");
    },

    // 隐藏详情
    hide_details: function() {
        $(this.details_info_title).hide();
        $(this.productinfo_div).hide();
    }
}

// 缺货状态下 - 您可能感兴趣的商品
bg.common.goods_oos.favorites_goods = {
    fg:      "#favorites_goods",
    fg_list: "#favorites_goods_list",

    // 显示感兴趣的商品
    fg_show: function() {
        var favorites_html = $(this.fg_list).html();
        $(".fg_list", this.fg).html(favorites_html);
        $("img", this.fg).each(function(){
            $(this).attr("src", $(this).attr("original"));
        });        
        
        // 您可能感兴趣的商品 加载后执行滚动js
        bg.utils.loadjs('http://s3.mb-go.com/pub7/style/js/jquery.jcarousel.js', function(){
            $(".fg_list ul", this.fg).jcarousel();
        });
    },

    // 隐藏感兴趣的商品
    fg_hide: function() {
        $(this.fg).hide();
    },

    // 调用
    init: function() {
        if ($("li", this.fg_list).length > 1) {
            this.fg_show();
        }
        else {
            this.fg_hide();
        }
    }

}

// 缺货状态下 - 浏览了该商品的顾客最终购买了
bg.common.goods_oos.final_bought = {
    fb: "#final_bought",

    // 显示顾客最终购买了
    fb_show: function() {
        $(this.fb).show();
    },

    // 顾客最终购买了 tab效果
    fb_tab: function() {
        var _fb     = this.fb,
            _li     = ".fb_menu li",
            _con    = ".recommend_list",
            _active = "active";

        // tab第一个内容区域默认显示图片
        $(_fb).find(_con).eq(0).find("img").each(function() {
          if ($(this).attr("src") != $(this).attr("original")) {
            $(this).attr("src", $(this).attr("original"));
          }
        });

        // tab效果
        $(_fb).find(_li).each(function(i){
            $(this).click(function(){
                $(this).addClass(_active).siblings().removeClass(_active);
                $(_fb).find(_con).eq(i).show().siblings().hide();
                
                // 点击tab时转化图片url
                $(_fb).find(_con).eq(i).find("img").each(function() {
                  if ($(this).attr("src") != $(this).attr("original")) {
                    $(this).attr("src", $(this).attr("original"));
                  }
                });
            });
        });
    },


        


    // 调用
    init: function() {
        this.fb_show();
        this.fb_tab();
    }
}

var goods = new Object()
/**
+----------------------------------------------------------
* 添加购物车
+----------------------------------------------------------
*/
goods.asubmit = function() {
    var options = {
		url: consts('act') + '/Cart/cartAjax?time=' + Math.random() + '&callback=?&type=add',
		type: 'get',
		dataType: 'json',
		success: function(responseText, statusText) {
			if(responseText.error != 0) {
				alert(responseText.mess);
				return;
			}
			if(responseText.error == 8) {
				_common_box('请您登录后继续刚才的操作');
				pop_login(0,'');
			}
			jQuery.getJSON(consts('act') + '/Cart/getCartInfo?time=' + Math.random() + '&callback=?', function(_data) {
				if(_data.status == 1) {
					_BuyNumJson();
					$('#open_num_tip').html(_data.goodsNumber);
					$('#open_money_tip').html(_data.sum);
				}
			})
			$('#light_box').show();
		}
	};
    $('#form_buy').ajaxSubmit(options);
}

/**
+----------------------------------------------------------
* 添加购物车【新】
* 2014-6-12
+----------------------------------------------------------
*/
goods.addToCart = function() {
	var params = $('#form_buy').serialize();
	$.getJSON( consts('act')+"/Cart/addToCart?time=" + Math.random()+"&callback=?", params, function(responseText,statusText) {
			if(responseText.error != 0) {
				alert(responseText.mess);
				return;
			}
			if(responseText.error == 8) {
				_common_box('请您登录后继续刚才的操作');
				pop_login(0,'');
			}
			jQuery.getJSON(consts('act') + '/Cart/getCartInfo?time=' + Math.random() + '&callback=?', function(_data) {
				if(_data.status == 1) {
					_BuyNumJson();
					$('#open_num_tip').html(_data.goodsNumber);
					$('#open_money_tip').html(_data.sum);
				}
			});
			$('#light_box').show();
	});
}

/**
+----------------------------------------------------------
* 添加收藏夹
* goods_sn   商品6位码
* ctype      渠道类型：wap,默认banggo
+----------------------------------------------------------
*/
function addCollect(goods_sn, type , beh_id, ctype){
	var params={goods_sn:goods_sn,beh_id:beh_id};
	$.ajax({type: "GET",url: consts('act')+"/Ajax/cartAjax?time="+Math.random()+"&callback=?&ajaxtype=add_"+type,data: params,dataType :"json",cache :"false",success : function(data,textStatus) {
		var str=type=='collect'?'收藏':'分享';
		switch(data){
			case 1:
				alert('成功加入'+str+'！');
				$("#collect_num").html($("#collect_num").html()-(-1));
				break;
			case 2:
				if( ctype == 'wap' ){
					window.location.href=consts('m')+"/login?u="+window.location.href;
				}else{
					_common_box('请您登录后继续刚才的操作');
					pop_login(1,'');
				}
				break;
			case 3:
				alert('您已添加过'+str+'！');
				break;
		}
	},error:function(){
		alert("加载失败");
	}});
}

/**
+----------------------------------------------------------
* 到货通知
* goods_sn   商品6位码
* ctype      渠道类型：wap,shop,默认banggo
+----------------------------------------------------------
*/
function arrival_notice(goods_sn, ctype){
	jQuery.getJSON(consts('act')+'/Goods/arrivalNotice?callback=?', {},function(jsondata){
		if( ctype == 'shop' ) jsondata.code = 1;
		if(jsondata.code == 3){
			if( ctype == 'wap' ){
				window.location.href=consts('m')+"/login?u="+window.location.href;
			}else{
				_common_box('请您登录后继续刚才的操作');
				pop_login(1,'');
			}
		}else{
			_common_box('<font color="#cf0b0b">到货通知我</font>');
			var _html = "";
			if( ctype != 'shop' ) _html +='　请选择适合自己的通信方式，两者选择一种即可<br>';
			_html +='<div style="padding-top:20px">　短信通知我：<input type="text" name="n_mobile" id="n_mobile"';
			if(jsondata.mobile == '' || jsondata.mobile == null){
				_html += "value='请输入手机号码！' onfocus='if(this.value == \"请输入手机号码！\") this.value=\"\"'";
			}else{
				_html += 'value="' + jsondata.mobile + '"';
			}
			_html += ' style="height:20px;color:#666"> ';
			if( jsondata.ischeckmobile == 0 && ctype != 'shop' ){
				_html += '<a href="' + consts('member') + '/MemberInfo/checkMobile" target="_blank" style="color:#CC0000">认证手机</a>送积分！';
			}
			_html += '</div>';
			if( ctype != 'shop' ){
				_html +='<div style="padding-top:10px">　邮件通知我：<input type="text" name="n_email" id="n_email"';
				if (jsondata.email == '' || jsondata.email == null){
					_html += "value='请输入邮箱！' onfocus='if(this.value == \"请输入邮箱！\") this.value=\"\"'";
				}else{
					_html += 'value="' + jsondata.email + '"';
				}
				_html += ' style="height:20px;color:#666"> ';
				if(jsondata.ischeckemail == 0){
					_html += '<a href="' + consts('member') + '/MemberInfo/checkEmail" target="_blank" style="color:#CC0000">认证邮箱</a>送积分！';
				}
				_html += '</div>';
			}
			_html +='<div style="padding:15px 85px 20px"><a class="btn btn_important" onClick="arrival_notice_send('+goods_sn+',\''+ctype+'\')" ><span>确　定</span></a></div>';
			$("#pop_content .pop_content_inner").html(_html);
		}
	});
}

function arrival_notice_send(goods_sn,ctype) {
	var n_mobile = trim($('#n_mobile').val());
	if(n_mobile == '请输入手机号码！') n_mobile = '';
	var n_email = trim($('#n_email').val());
	if(n_email == '请输入邮箱！') n_email = '';
	if(n_mobile=='' && n_email=='') {
		alert('短信和邮件不能同时为空！');
		return false;
	}
	if(n_mobile != '' && !Utils.isMobile(n_mobile)) {
		alert('手机号码不正确！');
		return false;
	}
	if(n_email != '' && !Utils.isEmail(n_email)) {
		alert('邮件不正确！');
		return false;
	}
	jQuery.getJSON(consts('act')+'/Goods/arrivalNotice?callback=?', {goods_sn:goods_sn,mobile:n_mobile,email:n_email,ctype:ctype},function(jsondata) {
		if (jsondata.code == 1) {
			var _html = '';
			_html += '<div style="text-align:center;color:#cf0b0b;font-size:14px;font-weight:bold;padding:10px 0px">恭喜，预定成功！</div>';
			_html += '<div>商品补货后会第一时间通知您，请留意您的手机短信或邮件信息。</div>';
			_html += '<div style="text-align:center;padding:10px 0px 5px 0px"><a class="btn btn_important" onClick="close_pop_window()" ><span>关　闭</span></div>';
			$("#pop_content .pop_content_inner").html(_html);
		}
	});
}

/**
+----------------------------------------------------------
* 显示价格弹层
+----------------------------------------------------------
* @param  string   goodsSn      商品编码
* @param  string   type         类型：详情[detail],团购[tuan],秒杀[second],默认[current]
* @param  string   title        弹层标题
+----------------------------------------------------------
*/
function popColorSizePrice( goodsSn, type, title ){
	var title = title ? title : '查看商品', params = { goods_sn:goodsSn, type:type };
	$.getJSON( consts('act')+"/GoodsColorSize/getColorSizePrice?callback=?",params,function(data,textStatus){
		_common_box(title);
		$("#pop_window").css({"margin-left":"-295px","width":"590px"});
		$("#pop_content").css({"width":"580px"});
		$("#pop_content .pop_content_inner").empty();
		$("#pop_content .pop_content_inner").html(data);
	});
}

/**
+----------------------------------------------------------
* 显示价格区域
+----------------------------------------------------------
* @param  string   goodsSn      商品编码
* @param  string   colorCode    商品颜色
* @param  string   type         类型：详情[detail],团购[tuan],秒杀[second],默认[current]
+----------------------------------------------------------
*/
function getColorSizePrice( goodsSn, colorCode, type, expandInfo ){
	var params = { goods_sn:goodsSn, color_code:colorCode, type:type, expandInfo:expandInfo };
	$.getJSON( consts('act')+"/GoodsColorSize/getColorSizePrice?callback=?",params,function(data,textStatus){
		$( "#getColorSizePrice" ).html(data);
	});
}

/**
+----------------------------------------------------------
* 选择尺码颜色
+----------------------------------------------------------
* @param  string   goodsSn      商品编码
* @param  string   colorCode    商品颜色
* @param  string   sizeCode     商品尺码
+----------------------------------------------------------
*/
function chooseColorSize( goodsSn, colorCode, sizeCode, type ){
	var params = { goods_sn:goodsSn, color_code:colorCode, size_code:sizeCode, type:type };
	$.getJSON( consts('act')+"/GoodsColorSize/chooseColorSize?callback=?",params,function(data,textStatus){
		$( ".colorSize" + goodsSn ).html(data);
		$( "#inventory_number" + goodsSn ).html( '(库存剩余 ' + $( "#inventoryNumber" + goodsSn ).val() + ' 件)' );
		$( "#sale_price" + goodsSn ).html( $( "#salePrice" + goodsSn ).val() );
		if( typeof( $( "#vip_price" + goodsSn ) ) != 'undefined' ) $( "#vip_price" + goodsSn ).html( $( "#vipPrice" + goodsSn ).val() );
		if( typeof( $( "#svip_price" + goodsSn ) ) != 'undefined' ) $( "#svip_price" + goodsSn ).html( $( "#svipPrice" + goodsSn ).val() );
		if( typeof( $( "#staff_price" + goodsSn ) ) != 'undefined' ) $( "#staff_price" + goodsSn ).html( $( "#staffPrice" + goodsSn ).val() );
	});
}

/**
+----------------------------------------------------------
* 改变图片
+----------------------------------------------------------
* @param  string   id           class或id
* @param  string   imgUrl       图片地址
+----------------------------------------------------------
*/
function changeImgUrl( id, imgUrl ) {
	$(id).attr('src',imgUrl);
}

/**
+----------------------------------------------------------
* 减少数量
+----------------------------------------------------------
* @param  string   obj           当前对象
+----------------------------------------------------------
*/
function minusNumber( obj ) {
	var _obj = $(obj).next("input[name^='goods_number']"), number = _obj.val();
	if( number > 1 ){
		_obj.val(--number);
	}else {
		showError();
		$("#hasInventory").text('购买数量不能小于1');
	}
}

/**
+----------------------------------------------------------
* 增加数量
+----------------------------------------------------------
* @param  string   obj           当前对象
+----------------------------------------------------------
*/
function addNumber( obj ) {
	var _obj = $(obj).prev("input[name^='goods_number']"), number = _obj.val();
	if( number < 20 ) {
		_obj.val(++number);
	}else{
		showError();
		$("#hasInventory").text('单件商品限购20件');
	}
}

/**
+----------------------------------------------------------
* 检验数字
+----------------------------------------------------------
* @param  string   obj           当前对象
+----------------------------------------------------------
*/
function checkNumber( obj ) {
	//console.log(obj);
	$(obj).keydown(function (event) {
		if( ( (event.keyCode > 47) && (event.keyCode < 58) ) || (event.keyCode == 8) || ( (event.keyCode > 95) && (event.keyCode < 106) ) ) {
			return true;
		} else {
			return false;
		}
	});
}

/**
+----------------------------------------------------------
* 关闭窗口
+----------------------------------------------------------
* @param  string   obj           当前对象
+----------------------------------------------------------
*/
function buyBagClose( obj ) {
	$(obj).hide();
}


